package com.expmle.surfaceviewdemo

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * @Author: YuanPeikai
 * @CreateDate: 2020/6/23 15:57
 * @Description: surfaceView 使用的基本模板，几乎都按这个套路走
 */
class SurfaceViewTempalte : SurfaceView, SurfaceHolder.Callback, Runnable {

    private lateinit var mHolder: SurfaceHolder
    private var mCanvas: Canvas? = null;


    private lateinit var t: Thread;


    private var isRunning: Boolean = false;


    constructor(context: Context?) : this(context, null)


    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)


    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {

        mHolder = holder;
        mHolder.addCallback(this);

        isFocusable = true;
        isFocusableInTouchMode = true;
        keepScreenOn = true;

    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        isRunning = false;
    }

    // 线程池，保证线程以队列方式一个一个执行，不出现内存溢出
    private val mExecutorService: ExecutorService = Executors.newSingleThreadExecutor()

    override fun surfaceCreated(holder: SurfaceHolder?) {

        isRunning = true;
        t = Thread(this)
        t.start()
        //mExecutorService.execute(this);
    }

    override fun run() {

        while (isRunning) {
            draw();
        }

    }

    private fun draw() {

        try {
            mCanvas = mHolder.lockCanvas();
            if (mCanvas != null) {
                //绘制界面，在这里写
            }

        } catch (e: Exception) {
            mCanvas = null;
            e.printStackTrace()
        } finally {
            if (mCanvas != null) {
                mHolder.unlockCanvasAndPost(mCanvas)
            }
        }


    }


}